package com.howard.modules.person.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONArray;

import org.apache.struts2.ServletActionContext;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.howard.modules.person.bean.City;
import com.howard.modules.person.bean.Person;
import com.howard.modules.person.bean.Province;
import com.howard.modules.person.service.PersonService;
import com.howard.modules.user.User;
import com.howard.modules.user.service.UserService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.Preparable;

@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class PersonAction extends ActionSupport implements Preparable{
	private static final long serialVersionUID = 1L;
	@Resource
	private PersonService personService;
	
	@Resource
	private UserService userService;
	
	private String message;
	private List<Person> personList;
	private Person person;
	private JSONArray jsonValidateReturn;
	private List dataList;
	private boolean jsonReturn;
	private List<Province> provinceList;
	private List<City> cityList;
	
	public Person getPerson() {
		return person;
	}
	public void setPerson(Person person) {
		this.person = person;
	}
	
	public List getDataList() {
		return dataList;
	}
	public void setDataList(List dataList) {
		this.dataList = dataList;
	}
	//此方法在执行action方法之前调用 要实现Preparable接口
	public void prepare() throws Exception { 
//		System.out.println("PersonAction prepare() excuted");
		//此处是为了清除token的错误信息，防止重复提交后，不能再请求的错误
		this.clearErrorsAndMessages();
	} 
	
	/**
	 * 人员列表显示
	 */
	public String list(){
		this.personList = personService.getList();
		return SUCCESS;
	}
	/**
	 * 人员添加界面
	 */
	private void initCity(){
		cityList=new ArrayList<City>();
		City c1=new City(1l,1l,"广州");
		City c2=new City(2l,1l,"惠州");
		City c3=new City(3l,1l,"中山");
		City c4=new City(4l,2l,"苏州");
		City c5=new City(5l,2l,"南京");
		City c6=new City(6l,2l,"扬州");
		City c7=new City(7l,2l,"无锡");
		cityList.add(c1);
		cityList.add(c2);
		cityList.add(c3);
		cityList.add(c4);
		cityList.add(c5);
		cityList.add(c6);
		cityList.add(c7);
	}
	
	private void initProvince(){
		provinceList=new ArrayList<Province>();
		Province p1=new Province(1l,"广东");
		Province p2=new Province(2l,"江苏");
		provinceList.add(p1);
		provinceList.add(p2);
	}
	
	public void initPerson(){
		personList=new ArrayList<Person>();
		Person p1=new Person("aaa","123456");
		Person p2=new Person("bbb","123456");
		Person p3=new Person("中国","123456");
		personList.add(p1);
		personList.add(p2);
		personList.add(p3);
	}
	
	public String toLogin(){
//		System.out.println("PersonAction toLogin!!!!!");
//		HttpServletRequest request=ServletActionContext.getRequest();
//		String sessionToken=(String)request.getAttribute("struts.token");	
//		String requestToken=request.getParameter("struts.token");
//		System.out.println("sessionToken="+sessionToken);
//		System.out.println("requestToken="+requestToken);
		return SUCCESS;
	}
	
	public String toInsertPage(){
		cityList=new ArrayList<City>();
		return SUCCESS;
	}
	/**
	 * 人员添加
	 */
	public String insert(){
		Person p=this.person;
		MessageDigest md5;
		try {
			md5 = MessageDigest.getInstance("MD5");
			md5.update(p.getPassword().getBytes());
			byte[] result=md5.digest();
			String passwordMd5=new BigInteger(1, result).toString(16);
			p.setPassword(passwordMd5);
			
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		
		this.personService.save(p);
		this.message="添加成功";
		return SUCCESS;
	}
	
	public void validateInsert(){
		if(person.getName().equals("howard")){
//			this.addFieldError("person.name", this.getText("person.name.invalid",new String[] { person.getName() }));
			this.addFieldError("person.name",this.getText("invalid.fieldvalue.person.name",new String[] { person.getName() }));
			this.addActionError(this.getText("invalid.fieldvalue.person.name",new String[] { person.getName() }));
		}
	}
	
	public void validateNameAjax() throws IOException{
		String username=ServletActionContext.getRequest().getParameter("username");
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		initPerson();
		for(Person s:personList){
			if(s.getName().equals(username)){
				jsonReturn=false;
				out.print(jsonReturn);
				out.flush();
				out.close();
				return;
			}
		}
		jsonReturn=true;
		out.print(jsonReturn);
		out.flush();
		out.close();
		return;
	}
	
	public void findSubClassAjax() throws IOException{
		String superId=ServletActionContext.getRequest().getParameter("superId");
		List<City> newCityList=new ArrayList<City>();
		
		if(superId!=null && !superId.equals("")){
			Long super_id=Long.parseLong(superId);
			jsonValidateReturn=new JSONArray();
			initCity();
//			System.out.println("this.cityList.size="+this.cityList.size());
			for(City c:cityList){
				if(c.getParentId()==super_id){
					newCityList.add(c);
				}
			}
		}
		jsonValidateReturn=JSONArray.fromObject(newCityList);
		HttpServletResponse response=ServletActionContext.getResponse();
		response.setCharacterEncoding("UTF-8");
		PrintWriter out=response.getWriter();
		out.print(jsonValidateReturn.toString());
		out.flush();
		out.close();
	}
	
	public String findSubClassAjax2() throws IOException{
		String superId=ServletActionContext.getRequest().getParameter("superId");
		List<City> newCityList=new ArrayList<City>();
		dataList=new ArrayList();
		if(superId!=null && !superId.equals("")){
			Long super_id=Long.parseLong(superId);
			jsonValidateReturn=new JSONArray();
			initCity();
			for(City c:cityList){
				if(c.getParentId()==super_id){
					newCityList.add(c);
					dataList.add(c);
				}
			}
		}
		
		jsonValidateReturn=JSONArray.fromObject(newCityList);
		return SUCCESS;
	}
	
	
	public String findSubClassAjax3() throws IOException{
		String superId=ServletActionContext.getRequest().getParameter("superId");
		List<City> newCityList=new ArrayList<City>();
		
		if(superId!=null && !superId.equals("")){
			Long super_id=Long.parseLong(superId);
			jsonValidateReturn=new JSONArray();
			initCity();
			for(City c:cityList){
				if(c.getParentId()==super_id){
					newCityList.add(c);
				}
			}
		}
		jsonValidateReturn=JSONArray.fromObject(newCityList);
		ServletActionContext.getRequest().setAttribute("outString", jsonValidateReturn);
		return SUCCESS;
	}
	public String show(){
		return SUCCESS;
	}
	
	public List<Person> getPersonList() {
		return personList;
	}
	public void setPersonList(List<Person> personList) {
		this.personList = personList;
	}
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}
	
	public JSONArray getJsonValidateReturn() {
		return jsonValidateReturn;
	}
	
	public void setJsonValidateReturn(JSONArray jsonValidateReturn) {
		this.jsonValidateReturn = jsonValidateReturn;
	}
	public boolean isJsonReturn() {
		return jsonReturn;
	}
	public void setJsonReturn(boolean jsonReturn) {
		this.jsonReturn = jsonReturn;
	}
	public List<Province> getProvinceList() {
		return provinceList;
	}
	public void setProvinceList(List<Province> provinceList) {
		this.provinceList = provinceList;
	}
	public List<City> getCityList() {
		return cityList;
	}
	public void setCityList(List<City> cityList) {
		this.cityList = cityList;
	}
	
	
}
